// main.js

var code = '127105';

var BASE_DIR = context.getFilesDir().getAbsolutePath() + "/";
var MODULE_LOCAL = BASE_DIR + "Module/moniterModule.js"; 
var PNG_LOCAL = BASE_DIR + "Assets/gd.png";

// ========== 以下下载逻辑保持不变 ==========
function ensureDir(path) {
    var dir = new java.io.File(path).getParentFile();
    if (dir && !dir.exists()) {
        dir.mkdirs();
    }
}

function fileExists(path) {
    return files.exists(path);
}

function downloadFile(url, savePath, name) {
    ensureDir(savePath);
    try {
        var res = http.get(url, { timeout: 8000 });
        if (res.statusCode === 200) {
            files.writeBytes(savePath, res.body.bytes());
            return true;
        }
    } catch (e) { }
    return false;
}

function ensureModule() {
    if (fileExists(MODULE_LOCAL) && fileExists(PNG_LOCAL)) {
        return true;
    }

    if (typeof http === 'undefined') {
        toast("❌ 请开启【网络】权限");
        return false;
    }

    var tasks = [];
    if (!fileExists(MODULE_LOCAL)) {
        tasks.push({
            url: "https://gitee.com/dalilb/autox.js_moniter/raw/master/moniterModule.js",
            path: MODULE_LOCAL,
            name: "模块"
        });
    }
    if (!fileExists(PNG_LOCAL)) {
        tasks.push({
            url: "https://gitee.com/dalilb/autox.js_moniter/raw/master/gd.png",
            path: PNG_LOCAL,
            name: "图标"
        });
    }

    for (var i = 0; i < tasks.length; i++) {
        var task = tasks[i];
        if (!downloadFile(task.url, task.path, task.name)) {
            toast("❌ 下载失败: " + task.name);
            return false;
        }
    }
    return true;
}
// ========== 下载逻辑结束 ==========

// ========== 主程序逻辑 ==========
(function main() {
    log("🚀 启动...");

    if (!ensureModule()) {
        exit();
    }

    sleep(500);

    // 引入数据模块（使用下载后的本地路径）
    var dataModule;
    try {
        dataModule = require(MODULE_LOCAL); 
    } catch (e) {
        toast("❌ 模块加载失败");
        log("错误:", e.message);
        exit();
    }

    var n = 0;
    var showFullData = false;

    // 悬浮窗 UI（适配 PNG_LOCAL 路径）
    var w = floaty.rawWindow(
        <frame>
            <horizontal id="bg" gravity="center" bg="#000000" padding="10px 72px 10px 0px">
                <vertical weight="1">
                    <text id="text1" gravity="left" textSize="11sp" textColor="#F7DBA9"/>
                </vertical>
                <frame id="colorBlock" w="40px" h="40px" bg="#000000" marginLeft="20px"/>
            </horizontal>
            <img id="gd" scaleType="center" w="120px" h="129px" layout_gravity="bottom|right" marginRight="20px"
                 src={"file://" + PNG_LOCAL}/>
        </frame>
    );

    w.setSize(-1, 180);
    w.setTouchable(true);

    var x = 0, y = 0, windowY, downTime;

    w.gd.setOnTouchListener(function (view, event) {
        switch (event.getAction()) {
            case event.ACTION_DOWN:
                x = event.getRawX();
                y = event.getRawY();
                windowY = w.getY();
                downTime = new Date().getTime();
                return true;
            case event.ACTION_MOVE:
                w.setSize(1080, windowY + Math.max(event.getRawY() + 50, 160));
                return true;
            case event.ACTION_UP:
                if (Math.abs(event.getRawY() - y) < 5 && Math.abs(event.getRawX() - x) < 5) {
                    onClick();
                }
                return true;
        }
        return true;
    });

    w.colorBlock.click(function () {
        exit();
    });

    function onClick() {
        showFullData = !showFullData;
    }

    // 主循环
    setInterval(function () {
        var qtData = dataModule.fetchQtData(code);
        var dataText = qtData ? formatQtDisplay(qtData) : "null";

        var jichaText = getJiCha();
        var imValue = extractIM(jichaText);
        var color = getColorByIM(imValue);

        ui.run(function () {
            w.text1.setText(dataText + "  " + jichaText);
            w.colorBlock.attr("bg", color);
        });

        n++;
    }, 2000);

    // 显示格式化
    function formatQtDisplay(qt) {
        if (showFullData) {
            return qt.sell1 + "：" + qt.sell1_volume + ", 'C:'" + qt.change_percent + "\r\n" +
                   qt.buy1 + "：" + qt.buy1_volume;
        } else {
            return qt.sell1;
        }
    }

    // 提取 IM 值
    function extractIM(str) {
        var match = str.match(/IM:\s*([+-]?\d+(\.\d+)?)/);
        return match ? parseFloat(match[1]) : NaN;
    }

    // 根据 IM 返回颜色
    function getColorByIM(im) {
        if (isNaN(im)) return "#888888";
        if (im <= 130) return "#ff0000";
        if (im >= 230) return "#00ff00";
        if (im === 180) return "#000000";

        var r, g, b;
        if (im < 180) {
            var ratio = (im - 130) / 50;
            r = Math.floor(255 * (1 - ratio));
            g = b = 0;
        } else {
            var ratio = (im - 180) / 50;
            r = b = 0;
            g = Math.floor(255 * ratio);
        }

        var hr = ("0" + r.toString(16)).slice(-2);
        var hg = ("0" + g.toString(16)).slice(-2);
        var hb = ("0" + b.toString(16)).slice(-2);
        return "#" + hr + hg + hb;
    }

    // 获取基差
function getJiCha() {
    try {
        var sinaData = dataModule.fetchSinaIndexData();
        var hs300Spot = sinaData['s_sh000300'];
        var zz1000Spot = sinaData['s_sh000852'];

        if (hs300Spot === undefined || zz1000Spot === undefined) {
            return "IM: --";
        }

        var joData = dataModule.fetchJijinhaoData();
        if (!joData) return "IM: --";

        // 兼容 ES5：避免使用 ?. 操作符
        var ifFuture = (joData["JO_338503"] && joData["JO_338503"].q63) 
            ? parseFloat(joData["JO_338503"].q63) : NaN;
        var imFuture = (joData["JO_338545"] && joData["JO_338545"].q63) 
            ? parseFloat(joData["JO_338545"].q63) : NaN;

        if (isNaN(ifFuture) || isNaN(imFuture)) return "IM: --";

        var jiCha_IF = (hs300Spot - ifFuture).toFixed(2);
        var jiCha_IM = (zz1000Spot - imFuture).toFixed(2);

        if (showFullData) {
            if (parseFloat(jiCha_IM) < 130) {
                toastAction();
            }
            return "IF: " + jiCha_IF + "  IM: " + jiCha_IM;
        } else {
            return "IM: " + jiCha_IM;
        }
    } catch (e) {
        console.error("基差计算失败:", e.message);
        return "IM: --";
    }
}
    // 提示动作
    function toastAction() {
        swipe(500, 1510, 520, 330, 180);
        device.setBrightness(0);
        sleep(600);
        device.setBrightness(150);
        sleep(1200);
        device.setBrightness(0);
        sleep(600);
        device.setBrightness(10);
    }
})();